//
//  LGLungFollowProjectController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/7/8.
//  选择项目、评估项、宣教等

#import "LGLungFollowProjectController.h"
#import "LGLungFollowProjectCell.h"
@interface LGLungFollowProjectController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UITextField *searchTF;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *bottomView;
/**   */
@property (nonatomic , strong)UIButton *selectAllBtn;
/**   */
@property (nonatomic , strong)UILabel *countLabel;
/**   */
@property (nonatomic , strong)UIButton *saveBtn;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *codeArray;
/**   */
@property (nonatomic , strong)NSMutableArray *nameArray;

@end

@implementation LGLungFollowProjectController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.searchTF];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.selectAllBtn];
    [self.bottomView addSubview:self.countLabel];
    [self.bottomView addSubview:self.saveBtn];
    [self requestData];
}

-(void)requestData{
    NSString *content = (self.searchTF.text.length>0)?self.searchTF.text:@"";
    [RequestUtil withPOST:self.action parameters:@{@"keyword":content} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.dataArray = returnData;
            [self caculateSelectCount];
            [self.tableView reloadData];
            if (self.codeArray.count<self.dataArray.count) {
                self.selectAllBtn.selected = NO;
            }else{
                for (NSDictionary *tempDic in self.dataArray) {
                    if ([tempDic.allKeys containsObject:@"code"]) {
                        NSString *code = LGNSString(tempDic[@"code"]);
                        if (![self.codeArray containsObject:code]) {
                            self.selectAllBtn.selected = NO;
                            break;
                        }
                    }else{
                        NSInteger value = [tempDic[@"value"] integerValue];
                        if (![self.codeArray containsObject:@(value)]) {
                            self.selectAllBtn.selected = NO;
                            break;
                        }
                    }
                    
                }
                self.selectAllBtn.selected = YES;
            }
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.codeArray = [NSMutableArray arrayWithArray:dataDic[@"codes"]];
    self.nameArray = [NSMutableArray arrayWithArray:dataDic[@"names"]];
}


-(void)textFieldEditingChanged:(UITextField *)textField{
    [self requestData];
}

//全选
-(void)selectAllBtnAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        //全选
        for (NSDictionary *tempDic in self.dataArray) {
            if ([tempDic.allKeys containsObject:@"value"]) {
                NSString *value = LGNSString(tempDic[@"value"]);
                if (![self.codeArray containsObject:value]) {
                    [self.codeArray addObject:@([value integerValue])];
                    [self.nameArray addObject:LGNSString(tempDic[@"title"])];
                }
            }else if([tempDic.allKeys containsObject:@"code"]){
                NSString *value = LGNSString(tempDic[@"code"]);
                if (![self.codeArray containsObject:value]) {
                    [self.codeArray addObject:LGNSString(tempDic[@"code"])];
                    [self.nameArray addObject:LGNSString(tempDic[@"name"])];
                }
            }
        }
    }else{
        //取消全选
        [self.codeArray removeAllObjects];
        [self.nameArray removeAllObjects];
    }
    
    [self.tableView reloadData];
    [self caculateSelectCount];
}

-(void)saveDataAction{
    if(self.codeArray.count == 0){
        [TooltipView showMessage:@"请选择项目" offset:0];
        return;
    }

    if (self.selectProjectSuccess) {
        self.selectProjectSuccess(@{@"codes":self.codeArray,@"names":self.nameArray});
    }
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)caculateSelectCount{
    NSString *content = [NSString stringWithFormat:@"已选 %ld 项",self.codeArray.count];
    self.countLabel.attributedText = [content attributeString:@{NSFontAttributeName:LGFontWeight(15, UIFontWeightMedium),NSForegroundColorAttributeName:[UIColor colorWithString:kThemeColor]} range:NSMakeRange(2, content.length-3)];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.row];
    NSString *code = [tempDic.allKeys containsObject:@"code"]?LGNSString(tempDic[@"code"]):LGNSString(tempDic[@"value"]);
    LGLungFollowProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    if ([tempDic.allKeys containsObject:@"code"]) {
        cell.iconBtn.selected = [self.codeArray containsObject:code]?YES:NO;
    }else{
        cell.iconBtn.selected = [self.codeArray containsObject:@([code integerValue])]?YES:NO;
    }
    
    cell.lineView.hidden = (indexPath.row == self.dataArray.count-1)?YES:NO;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.row];
    NSString *code = [tempDic.allKeys containsObject:@"code"]?LGNSString(tempDic[@"code"]):LGNSString(tempDic[@"value"]);
    NSString *name = [tempDic.allKeys containsObject:@"code"]?LGNSString(tempDic[@"name"]):LGNSString(tempDic[@"title"]);
    if ([tempDic.allKeys containsObject:@"code"]) {
        if ([self.codeArray containsObject:code]) {
            [self.codeArray removeObject:code];
            [self.nameArray removeObject:name];
        }else{
            [self.codeArray addObject:code];
            [self.nameArray addObject:name];
        }
    }else{
        NSInteger value = [code integerValue];
        if ([self.codeArray containsObject:@(value)]) {
            [self.codeArray removeObject:@(value)];
            [self.nameArray removeObject:name];
        }else{
            [self.codeArray addObject:@(value)];
            [self.nameArray addObject:name];
        }
    }
    [self.tableView reloadData];
    [self caculateSelectCount];
    if (self.codeArray.count<self.dataArray.count) {
        self.selectAllBtn.selected = NO;
    }else{
        for (NSDictionary *tempDic in self.dataArray) {
            if ([tempDic.allKeys containsObject:@"code"]) {
                NSString *code = LGNSString(tempDic[@"code"]);
                if (![self.codeArray containsObject:code]) {
                    self.selectAllBtn.selected = NO;
                    break;
                }
            }else{
                NSInteger value = [tempDic[@"value"] integerValue];
                if (![self.codeArray containsObject:@(value)]) {
                    self.selectAllBtn.selected = NO;
                    break;
                }
            }
            
        }
        self.selectAllBtn.selected = YES;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(12);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(12))];
    headView.topMargin = viewPix(8);
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(12);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(12))];
    footView.bottomMargin = viewPix(8);
    return footView;
}

#pragma mark
#pragma mark ====> 创建控件
-(UITextField *)searchTF{
    if(!_searchTF){
        _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(12), viewPix(6), Screen_W-viewPix(24), viewPix(32))];
        _searchTF.tintColor = [UIColor colorWithString:@"#333333"];
        _searchTF.textColor = [UIColor colorWithString:@"#333333"];
        _searchTF.backgroundColor = [UIColor whiteColor];
        _searchTF.textAlignment = NSTextAlignmentLeft;
        _searchTF.keyboardType = UIKeyboardTypeDefault;
        _searchTF.placeholder = @"输入关键信息搜索";
        _searchTF.cornerRidus = 5;
        _searchTF.font = LGFont(15);
        _searchTF.leftViewMode = UITextFieldViewModeAlways;
        _searchTF.leftView = [self textFieldLeftView];
        [_searchTF addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        
    }
    return _searchTF;
}
-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewPix(44), Screen_W, Screen_H-topBarHeight-viewPix(156)-bottomSafeBarHeight/3.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGLungFollowProjectCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(8))];
    }
    return _tableView;
}

-(UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(112)-bottomSafeBarHeight/3.0)];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

-(UIButton *)selectAllBtn{
    if(!_selectAllBtn){
        _selectAllBtn = [UIButton buttonWithTitle:@"  全选" titleFont:LGFont(15) textColor:@"#333333" imageName:@"unselect20"];
        _selectAllBtn.frame = CGRectMake(viewPix(16), viewPix(10), viewPix(70), viewPix(30));
        [_selectAllBtn setImage:[UIImage imageNamed:@"selected20"] forState:UIControlStateSelected];
        [_selectAllBtn addTarget:self action:@selector(selectAllBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectAllBtn;
}

-(UILabel *)countLabel{
    if(!_countLabel){
        _countLabel = [UILabel lableWithText:@"" colorString:@"#909399" textFont:LGFont(15) textAlignment:NSTextAlignmentLeft lines:1];
        _countLabel.frame = CGRectMake(viewPix(86), viewPix(13), viewPix(150), viewPix(24));
    }
    return _countLabel;
}

-(UIButton *)saveBtn{
    if(!_saveBtn){
        _saveBtn = [UIButton buttonWithTitle:@"保存" topMargin:viewPix(49)];
        [_saveBtn addTarget:self action:@selector(saveDataAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}


-(UIView *)textFieldLeftView{
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(36), viewPix(32))];
    UIImageView *iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"searchGray16"]];
    iconView.frame = CGRectMake(viewPix(13), viewPix(8), viewPix(16), viewPix(16));
    [baseView addSubview:iconView];
    return baseView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
